module LockDown
  module Encryption
    require_dependency "openssl"
    require_dependency "base64"

    protected
      def self.encrypt(value)
        cr = value.dup
        if value.length < 24
          for i in value.length..23
            cr += "0"
            cr[i] = 0
          end
        end

        for i in 0..23
          cr[i] ^= LockDown::SECURITY_SALT[i]
        end
        
        sha = OpenSSL::Digest::SHA1.new
        sha << cr
        Base64.encode64(sha.digest).strip
      end#encrypt
  end # end Encryption module

  class Encryptor
    def initialize(attrs_to_manage)
      @attrs_to_manage = attrs_to_manage
    end

    def before_save(model)
      @attrs_to_manage.each do |field|
        model[field] = Sentry::SymmetricSentry.encrypt_to_base64(model[field],"k3.33_1$")
      end
    end

    def after_save(model)
      @attrs_to_manage.each do |field|
        model[field] = Sentry::SymmetricSentry.decrypt_from_base64(model[field],"k3.33_1$")
      end
    end

    alias_method :after_find, :after_save
  end
end # end LockDown module

class ActiveRecord::Base
  def self.encrypt(*attr_names)
    encryptor = LockDown::Encryptor.new(attr_names)

    before_save encryptor
    after_save encryptor
    after_find encryptor

    define_method(:after_find) {}
  end
end
